package com.heima.scan.service.Impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.heima.aliyun.AliyunGreenTemplate;
import com.heima.feign.ArticleClient;
import com.heima.file.MinIOTemplate;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemeda.entity.WmChannel;
import com.heima.model.wemeda.entity.WmNews;
import com.heima.model.wemeda.entity.WmUser;
import com.heima.scan.dao.WmNewsDao;

import com.heima.scan.service.WmChannelService;
import com.heima.scan.service.WmNewsService;
import com.heima.scan.service.WmSensitiveService;
import com.heima.scan.service.WmUserService;
import com.heima.utils.common.SensitiveWordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class WmNwsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsDao wmNewsDao;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @Autowired
    private MinIOTemplate minIOTemplate;

    @Autowired
    private WmSensitiveService wsensitiveService;

    @Autowired
    private ArticleClient articleClient;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmChannelService wmChannelService;


    //判断图片是否合规
    private boolean verifyImages(WmNews wmNews, List<String> images) {
        List<byte[]> Resultimage = images.stream().map(image -> minIOTemplate.downLoadFile(image)).collect(Collectors.toList());
        Map<String, String> ResultImage = aliyunGreenTemplate.greenImageScan(Resultimage);
        if ("pass".equals(ResultImage.get("suggestion"))) {
            wmNewsDao.update(wmNews);
            return true;
        }
        if ("block".equals(ResultImage.get("suggestion"))) {
            wmNews.setStatus(2);
            wmNews.setReason("图片涉嫌违规行为");
            wmNewsDao.update(wmNews);
            return false;
        }
        if ("review".equals(ResultImage.get("suggestion"))) {
            wmNews.setStatus(3);
            wmNews.setReason("图片需要人工审核");
            wmNewsDao.update(wmNews);
            return false;
        }
        return true;
    }


    //判断文本是否合规
    private boolean verifyText(WmNews wmNews, StringBuffer texts) {
        Map<String, Integer> map = SensitiveWordUtil.matchWords(texts + "");
        if (MapUtil.isNotEmpty(map)) {
            wmNews.setStatus(2);
            wmNews.setReason("有不合格信息:" + map.toString());
            wmNewsDao.update(wmNews);
            return false;
        }
        Map<String, String> result = aliyunGreenTemplate.greenTextScan(texts + "");
        if ("pass".equals(result.get("suggestion"))) {
            wmNewsDao.update(wmNews);
            return true;
        }
        if ("block".equals(result.get("suggestion"))) {
            wmNews.setStatus(2);
            wmNews.setReason("文本涉嫌违规行为");
            wmNewsDao.update(wmNews);
            return false;
        }
        if ("review".equals(result.get("suggestion"))) {
            wmNews.setStatus(3);
            wmNews.setReason("文本需要人工审核");
            wmNewsDao.update(wmNews);
            return false;
        }
        return true;
    }


    //文章审核
    public void check(Long id) {
        //通过前端id查询文章对象
        WmNews wmNews = wmNewsDao.queryById(id);
        if (wmNews == null) {
            return;
        }
        //文章状态不为1(待审核状态)直接返回
        if (wmNews.getStatus() != 1) {
            return;
        }
        //取出对象的文本数据和图片数据
        String content = wmNews.getContent();//内容(图片/文本)
        List<Map> maps = JSON.parseArray(content, Map.class);//内容(图片/文本)
        //内容图片
        List<String> resultimages = maps.stream().filter(map -> "image".equals(map.get("type"))).map(map -> map.get("value").toString()).collect(Collectors.toList());
        StringBuffer texts = new StringBuffer();//定义文本
        //取出内容文本
        String contentText = maps.stream().filter(map -> "text".equals(map.get("type"))).map(map -> map.get("value").toString() + ",").collect(Collectors.toList()).toString();
        //将标题文字和内容文字放到文本可变字符串中
        texts.append(contentText).append(wmNews.getTitle());
        String images1 = wmNews.getImages();
        String[] coverImages = images1.split(",");
        //遍历展示图片将图片url放入图片集合中
        for (String coverImage : coverImages) {
            resultimages.add(coverImage);
        }

        //判断文本是否合规
        if (!verifyText(wmNews, texts)) {
            return;
        }
        //判断图片是否合规
        if (!verifyImages(wmNews, resultimages)) {
            return;
        }

        //判断文章的发布时间是否小于当前时间
        Date publishTime = wmNews.getPublishTime();
        long resultTime = publishTime.getTime();//发布时间毫秒值
        long nowTime = System.currentTimeMillis();//当前时间毫秒值
        if (resultTime > nowTime) {
            //未到发布时间
            wmNews.setStatus(8);
            wmNews.setReason("文章审核通过,待发布");
            wmNewsDao.update(wmNews);
            return;
        }
        saveArticle(wmNews);
    }

    //时间已经到了发布时间,将数据发布到app端
    @Override
    public ResponseResult saveArticle(WmNews wmNews) {
        //将数据保存到app端数据表里
        //1.数据补全
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);
        articleDto.setNewsId(wmNews.getId());
        articleDto.setAuthorId(wmNews.getUserId());
        articleDto.setLayout(wmNews.getType());
//          articleDto.setAuthorName();//作者名字
        int userid = Integer.parseInt(wmNews.getUserId() + "");
        WmUser wmUser = wmUserService.queryById(userid);
        articleDto.setAuthorName(wmUser.getUsername());
//          articleDto.setChannelName();//频道名字
        WmChannel wmChannel = wmChannelService.queryById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());
        //fegin远程调用添加方法
        ResponseResult result = articleClient.save(articleDto);
        if (result.getCode() == 200) {
            wmNews.setStatus(9);
            wmNews.setReason("文章审核通过,已发布");
            wmNewsDao.update(wmNews);
        }
        return result;
    }
}


